let express = require("express");
let path = require("path");
let app = express();

app.use(express.urlencoded());
app.use(express.json());

//写处理跨域的中间件
app.use((request, response, next) => {
  //全部允许跨域
  // response.set('Access-Control-Allow-Origin','*')
  //允许单个跨域
  // response.set('Access-Control-Allow-Origin','http://127.0.0.1:5500')
  //允许几个跨域
  let arr = ["http://127.0.0.1:5500", "http://127.0.0.1:1010"];
  if (arr.includes(request.headers.origin)) {
    response.set("Access-Control-Allow-Origin", request.headers.origin);
    response.set("Access-Control-Allow-Headers", "*");
  }
  next();
});

//cors跨域
app.get("/userinfo", (request, response) => {
  let arr = ["http://127.0.0.1:5500", "http://127.0.0.1:1010"];
  if (arr.includes(request.headers.origin)) {
    response.set("Access-Control-Allow-Origin", request.headers.origin);
    response.send({
      code: 10000,
      msg: "查询成功",
      data: {
        name: "李博",
        age: 18,
        sex: "男",
      },
    });
  }
});

//jsonp跨域
app.get("/get", (request, response) => {
  console.log(request.query);
  let { userid, cb } = request.query;
  let data = {
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男",
    },
  };
  response.send(`${cb}(${JSON.stringify(data)})`);
});

//配置静态资源

app.get("/1", (request, response) => {
  let filePath = path.resolve(__dirname, "/创建aioxs实例.html");
  response.sendFile(filePath);
});

app.listen(1010, () => {
  console.log("running");
});
